package day1015;
import java.util.Arrays;

/**
 * @Author:galaxy_yan
 * @Date: 2022/10/15
 * @Time: 16:44
 * @Description
 */
public class MyStack {
    // 用一个数组去组织数据
    private int [] elementData;
    // 有效元素的个数
    private int size;
    // 定义一个数组默认的大小
    private final int DEFAULT_CAPACITY = 5;

    public MyStack() {
        this.elementData = new int[DEFAULT_CAPACITY];
    }

    public MyStack(int capacity) {
        if (capacity < 0) {
            throw new RuntimeException("数组容量不能小于0.");
        } else if (capacity > 0) {
            this.elementData = new int[capacity];
        } else {
            this.elementData = new int[DEFAULT_CAPACITY];
        }
    }

    public void push(int data) {
        // 数组是否需要扩容
        ensureCapacity();
        // 在size位置加入元素
        elementData[size]=data;
        size++;
    }

    private void ensureCapacity() {
        if (size == elementData.length) {
            this.elementData = Arrays.copyOf(elementData, elementData.length * 2);
        }
    }

    public int pop(){
        size--;
        return peek();
    }

    public int peek(){
        return elementData[size-1];
    }
}